import React from 'react'
import { Select, Input, Button, Table, Switch, Modal,message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import './ArticleListsTable.css'
import axios from '../../utils/http'
import { QUERYARTICLE, UPDATEARTICLE,DELETEARTICLEBYARTICLEID,DELETEARTICLEBYARTICLEIDS,SELECTARTICLEBYARTIVLECLA} from '../../utils/api'
// 下拉框
const { Option } = Select;
// 表格


class ArticleListsTable extends React.Component {
  constructor() {
    super()
    this.state = {
      // 表格头部
      columns: [
        {
          title: '编号',
          dataIndex: 'amId',
        },
        {
          title: '文章标题',
          dataIndex: 'amAt',
        },
        {
          title: '文章分类',
          dataIndex:'obj',
        },
        {
          title: '是否显示',
          render: (x, y, z) => <Switch defaultChecked={y.amDs} onChange={(state) => this.onChangeSwitch(x, y, z, state)} />
        },
        {
          title: '添加时间',
          dataIndex: 'amAddtime',
        },
        {
          title: '操作',
          render:(x,y,z) => <div style={{ color: '#4E6EF2' }}><span onClick={this.xgtable.bind(this,y)}>修改</span> <span onClick={this.confirm.bind(this,y)}>删除</span></div>,
        },
      ],
      //   表格数据
      data: [],
      // 分页条数
      pagination: {
        pageSize: 4
      },
      // 多选框 选中的索引
      selectedRowKeys:[],
        // 多选框 选中的id
        ObjData:[],

      //  根据文章类型名和文章标题查询文章
      chaxunData:{
        articleCname:'',
        amAt:''
      }


    }
  }
  // 跳转修改页面
  xgtable = (y) => {
    this.props.history.push({pathname:"/Home/wangZhan/ArticleLists/ModifyArticle",query: { name : y }});

  }

  // 生命周期
  componentWillMount() {
    axios({
      url: QUERYARTICLE,
      method: 'get'
    }).then(data => {
      for (let i = 0; i < data.data.data.length; i++) {
        data.data.data[i].key = data.data.data[i].amId
        data.data.data[i].obj=data.data.data[i].articleClass.articleCname
      }
      console.log(data);
      this.setState({
        data: [...data.data.data]
      })
    })
  }
  // Switch开关
  onChangeSwitch = async (x, y, z, checked) => {
    let Obj = { ...y }
    checked ? Obj.amDs = 1 : Obj.amDs = 0
    console.log(Obj);
    await axios({
      url: UPDATEARTICLE,
      method: 'post',
      data: Obj
    }).then(data => {
      console.log(data);
    })
    await axios({
      url: QUERYARTICLE,
      method: 'get'
    }).then(data => {
      for (let i = 0; i < data.data.data.length; i++) {
        data.data.data[i].key = data.data.data[i].amId
        data.data.data[i].obj=data.data.data[i].articleClass.articleCname
      }
      // console.log(data);
      this.setState({
        data: [...data.data.data]
      })
    })

  }

 //删除单个
// 删除弹框
confirm = (y) => {
  // console.log(y);
  Modal.confirm({
    title: '是否删除',
    icon: <ExclamationCircleOutlined />,
    content:y.amAt,
    okText: '确认',
    cancelText: '取消',
    onOk:this.delSure.bind(this,y)
  });
}

// 确定按钮
delSure(y){
  console.log(y.amId);
  axios({
    method:'get',
    url:DELETEARTICLEBYARTICLEID,
    params:{amId:y.amId}
  }).then(data=>{
    console.log(data);
    if(data.data.code===200){
      message.success('删除成功', 3);
      axios({
        url: QUERYARTICLE,
        method: 'get'
      }).then(data => {
        for (let i = 0; i < data.data.data.length; i++) {
          data.data.data[i].key = data.data.data[i].amId
          data.data.data[i].obj=data.data.data[i].articleClass.articleCname
        }
        console.log(data);
        this.setState({
          data: [...data.data.data]
        })
      })
    }else{
      message.error('删除失败',3);
    }
  })
}

// 表格首页
onSelectChange = (selectedRowKeys,key) => {
  let obj = []
  key.map(item=>{
    let newObj = {
      amId:item.amId
    }
    obj.push(newObj)
    return true
  })
  // console.log(obj);
  this.setState({
    ObjData:[...obj]
  })
  this.setState({
    selectedRowKeys:[...selectedRowKeys]
  })
};


// 批量删除
PilianDel=async()=>{
  console.log(this.state.ObjData);
    
  await axios({
    url:DELETEARTICLEBYARTICLEIDS,
    method:'post',
    data:this.state.ObjData
  }).then(data=>{
    // console.log(data);
    if (data.data.code===200) {
      message.success('删除成功', 3);
    }
  })

  await  axios({
    url: QUERYARTICLE,
    method: 'get'
  }).then(data => {
    for (let i = 0; i < data.data.data.length; i++) {
      data.data.data[i].key = data.data.data[i].amId
      data.data.data[i].obj=data.data.data[i].articleClass.articleCname
    }
    console.log(data);
    this.setState({
      data: [...data.data.data]
    })
  })



}

  // 下拉框
  onChange = (value) => {
    // console.log(`selected ${value}`);
    let obj = {...this.state.chaxunData}
    obj.articleCname=value
    this.setState({
      chaxunData:{...obj}
    })
  }

  // 获取搜索文章标题的值
  onChangeSsint=(e)=>{
    let obj = {...this.state.chaxunData}
    obj.amAt=e.target.value 
    this.setState({
      chaxunData:{...obj}
    })
  }

  // 提交值搜索
  Sousuo=()=>{
    console.log(this.state.chaxunData);
    axios({
      url:SELECTARTICLEBYARTIVLECLA,
      method:'get',
      params:{'amAt':this.state.chaxunData.amAt,'articleCname':this.state.chaxunData.amAt}
    }).then(data=>{
      for (let i = 0; i < data.data.data.length; i++) {
        data.data.data[i].key = data.data.data[i].amId
        data.data.data[i].obj=data.data.data[i].articleClass.articleCname
      }
      console.log(data);
      this.setState({
        data: [...data.data.data]
      }) 
    })
  }


  render() {
    // 表格首列
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      selections: [
        Table.SELECTION_ALL,
        Table.SELECTION_INVERT,
        {
          key: 'odd',
          text: 'Select Odd Row',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              // console.log(key);
              if (index % 2 !== 0) {
                return false;
              }
              return true;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
        {
          key: 'even',
          text: 'Select Even Row',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return true;
              }
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
      ],
    };


    return (
      <div className='ArticleListsTable'>
        <div className='Myheader'>
          <Select
            showSearch
            style={{ width: 200, margin: '0.5rem' }}
            // placeholder="全部分类"
            optionFilterProp="children"
            defaultValue={'全部分类'}
            onChange={this.onChange}
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            <Option value="全部分类">全部分类</Option>
            <Option value="帮助中心">帮助中心</Option>
            <Option value="文章咨询">文章咨询</Option>
            <Option value="文章推送">文章推送</Option>  
          </Select>
          <span>文章标题</span>
          <Input placeholder="请输入文章标题" onChange={this.onChangeSsint}/>
          <Button type="primary" onClick={this.Sousuo}>搜索</Button>
          <Button type="primary" onClick={this.PilianDel}>批量删除</Button>
        </div>
        <div className='mytable'>
          <Table pagination={this.state.pagination} rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.data} />
        </div>

      </div>
    )
  }

}

export default ArticleListsTable